package com.imut.lagain.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.FinalPassword;
import com.imut.lagain.service.IFinalPasswordService;
import com.imut.lagain.util.JwtUtil;
import com.imut.lagain.util.ValidationUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.*;
import jakarta.validation.Valid;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 最终密码控制器
 */
@RestController
@RequestMapping("/admin/passwords")
@RequiredArgsConstructor
@Validated
public class FinalPasswordController {
    private static final Logger log = LoggerFactory.getLogger(FinalPasswordController.class);

    
    private final IFinalPasswordService finalPasswordService;
    private final JwtUtil jwtUtil;
    
    /**
     * 获取当前激活密码
     * @param authorization JWT令牌
     * @return 当前激活密码
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentPassword(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            FinalPassword currentPassword = finalPasswordService.getCurrentActivePassword();
            
            response.put("success", true);
            response.put("data", currentPassword);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get current password", e);
            response.put("success", false);
            response.put("message", "获取当前密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 分页查询密码列表
     * @param authorization JWT令牌
     * @param page 页码
     * @param size 每页大小
     * @param isActive 是否激活
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 密码列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getPasswords(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
            @RequestParam(required = false) Boolean isActive,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Page<FinalPassword> pageParam = new Page<>(page, size);
            IPage<FinalPassword> passwordPage;
            if (isActive != null) {
                passwordPage = finalPasswordService.getPasswordsByActiveStatus(isActive, pageParam);
            } else if (startTime != null && endTime != null) {
                passwordPage = finalPasswordService.getPasswordsByCreateTimeBetween(startTime, endTime, pageParam);
            } else {
                passwordPage = finalPasswordService.page(pageParam);
            }
            
            response.put("success", true);
            response.put("data", passwordPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get passwords", e);
            response.put("success", false);
            response.put("message", "获取密码列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 创建新密码
     * @param authorization JWT令牌
     * @param request 创建密码请求
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createPassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody CreatePasswordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            FinalPassword password = finalPasswordService.createPassword(
                    request.getPasswordValue(), request.getDescription(), request.getIsActive());
            
            response.put("success", true);
            response.put("data", password);
            response.put("message", "密码创建成功");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to create password", e);
            response.put("success", false);
            response.put("message", "创建密码失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新密码激活状态
     * @param authorization JWT令牌
     * @param id 密码ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updatePasswordStatus(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id,
            @Valid @RequestBody UpdatePasswordStatusRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean updated = finalPasswordService.updatePasswordActiveStatus(id, request.getIsActive());
            
            if (updated) {
                response.put("success", true);
                response.put("message", "密码状态更新成功");
            } else {
                response.put("success", false);
                response.put("message", "密码不存在或更新失败");
            }
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to update password status", e);
            response.put("success", false);
            response.put("message", "更新密码状态失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 独占激活密码
     * @param authorization JWT令牌
     * @param id 密码ID
     * @return 激活结果
     */
    @PutMapping("/{id}/activate")
    public ResponseEntity<Map<String, Object>> activatePasswordExclusively(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean activated = finalPasswordService.activatePasswordExclusively(id);
            
            if (activated) {
                response.put("success", true);
                response.put("message", "密码激活成功");
            } else {
                response.put("success", false);
                response.put("message", "密码不存在或激活失败");
            }
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to activate password exclusively", e);
            response.put("success", false);
            response.put("message", "激活密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 停用所有密码
     * @param authorization JWT令牌
     * @return 停用结果
     */
    @PutMapping("/deactivate-all")
    public ResponseEntity<Map<String, Object>> deactivateAllPasswords(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            int deactivatedCount = finalPasswordService.deactivateAllPasswords();
            
            response.put("success", true);
            response.put("message", "所有密码已停用");
            response.put("deactivatedCount", deactivatedCount);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to deactivate all passwords", e);
            response.put("success", false);
            response.put("message", "停用所有密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 生成随机密码
     * @param authorization JWT令牌
     * @param request 生成密码请求
     * @return 生成的密码
     */
    @PostMapping("/generate")
    public ResponseEntity<Map<String, Object>> generatePassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody GeneratePasswordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            String generatedPassword;
            if ("uuid".equals(request.getType())) {
                generatedPassword = finalPasswordService.generateUUIDPassword();
            } else {
                generatedPassword = finalPasswordService.generateRandomPassword(request.getLength());
            }
            
            response.put("success", true);
            response.put("data", generatedPassword);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to generate password", e);
            response.put("success", false);
            response.put("message", "生成密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 验证密码
     * @param authorization JWT令牌
     * @param request 验证密码请求
     * @return 验证结果
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validatePassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody ValidatePasswordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean isValid = finalPasswordService.validatePassword(request.getPasswordValue());
            
            response.put("success", true);
            response.put("valid", isValid);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to validate password", e);
            response.put("success", false);
            response.put("message", "验证密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取密码统计信息
     * @param authorization JWT令牌
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getPasswordStats(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("activeCount", finalPasswordService.countActivePasswords());
            stats.put("totalCount", finalPasswordService.countTotalPasswords());
            stats.put("latestCreated", finalPasswordService.getLatestCreatedPassword());
            stats.put("latestUpdated", finalPasswordService.getLatestUpdatedPassword());
            
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get password stats", e);
            response.put("success", false);
            response.put("message", "获取密码统计失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除密码
     * @param authorization JWT令牌
     * @param id 密码ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean deleted = finalPasswordService.deletePassword(id);
            
            if (deleted) {
                response.put("success", true);
                response.put("message", "密码删除成功");
            } else {
                response.put("success", false);
                response.put("message", "密码不存在或删除失败");
            }
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to delete password", e);
            response.put("success", false);
            response.put("message", "删除密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    @Data
    public static class CreatePasswordRequest {
        @NotBlank(message = "密码值不能为空")
        @Size(min = 6, max = 50, message = "密码长度必须在6-50个字符之间")
        private String passwordValue;
        
        @Size(max = 200, message = "描述长度不能超过200个字符")
        private String description;
        
        private Boolean isActive = true;
        
        public String getPasswordValue() { return passwordValue; }
        public String getDescription() { return description; }
        public Boolean getIsActive() { return isActive; }
    }
    
    @Data
    public static class UpdatePasswordStatusRequest {
        @NotNull(message = "激活状态不能为空")
        private Boolean isActive;
        
        public Boolean getIsActive() { return isActive; }
    }
    
    @Data
    public static class GeneratePasswordRequest {
        @Pattern(regexp = "^(random|uuid)$", message = "类型只能是random或uuid")
        private String type = "random"; // random 或 uuid
        
        @Min(value = 6, message = "密码长度至少为6位")
        @Max(value = 50, message = "密码长度最多为50位")
        private Integer length = 16;
        
        public String getType() { return type; }
        public Integer getLength() { return length; }
    }
    
    @Data
    public static class ValidatePasswordRequest {
        @NotBlank(message = "密码值不能为空")
        private String passwordValue;
        
        public String getPasswordValue() { return passwordValue; }
    }
}

